<template>
  <div class="connect-set-box">
    <!-- <div class="connect-set-header">
      {{ $t('setting.buttonSet.text11') }}
    </div> -->
    <div class="pad-16">
      <el-form :model="nowItem" ref="formDom" label-position="top">
        <el-form-item 
          :label="$t('common.projectManage.taskTypeText')" 
          prop="event[0].type" 
          :rules="{ required: true, message: $t('common.base.pleaseSelect'), trigger: ['change'] }"
        >
          <el-select class="w-100-p" :value="nowItem.event[0].type" :placeholder="$t('common.base.pleaseSelect')" clearable @change="changeTaskType">
            <el-option v-for="item in taskTypeArr" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          :label="$t('setting.buttonSet.text12')" 
          prop="event[0].execute" 
          v-show="nowItem.event[0].type ===  ButtonSetDetailForButtonConcatEventEnum.Trigger" 
          :rules="{ required: true, message: $t('common.base.pleaseSelect'), trigger: ['change'] }"
        >
          <el-select class="w-100-p" :value="nowItem.event[0].execute[0]" :placeholder="$t('common.placeholder.input2')" clearable @change="changeTrigger">
            <el-option v-for="item in triggerArr" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item 
          :label="$t('setting.buttonSet.text16')" 
          prop="event[0].execute" 
          v-show="nowItem.event[0].type === ButtonSetDetailForButtonConcatEventEnum.Linker"
          :rules="[
            { required: true, message: $t('setting.buttonSet.text17'), trigger: ['change'] },
            { validator: customUrlValidator, trigger: ['blur'] }
          ]"
        >
          <el-input v-model="nowItem.event[0].execute[0]" :placeholder="$t('setting.buttonSet.text17')" clearable @input="changeLinker"></el-input>
        </el-form-item>
        <div class="form-item-box form-item-compilation" v-show="nowItem.event[0].type === ButtonSetDetailForButtonConcatEventEnum.Code">
          <el-button @click="openTestDialog">{{ $t('formSetting.jsCodeBlock.jsCodeTest') }}</el-button>
          <p>{{ $t('formSetting.jsCodeBlock.jsCodeTestBtnText') }}</p>
        </div>
      </el-form>
    </div>
    <run-test-dialog
      ref="compilationTestDialog"
      :field="codeField"
      @input="changeCode"
      :fields="fields"
    ></run-test-dialog>
  </div>
</template>
<script>
import { getCustomerFields } from '@src/api/CustomerApi';
import { getProductFields } from '@src/api/ProductApi';
import { defineComponent, ref, computed } from 'vue';
import { t } from '@src/locales';
import { filterFields } from '@src/component/form/util'
import { commonStore } from '@src/store/commonStore';
import { LINK_REG } from '@src/util/validator'
import { ButtonSetDetailForButtonConcatEventEnum, ButtonGetTriggerModuleEnum } from 'pub-bbx-global/pageType/dist/enum/ButtonSetEnum';
import runTestDialog from '@src/component/form/components/FormJsControl/components/compileEditor/runTestDialog.vue';
export default defineComponent({
  name: 'ButtonSetDetailConnectSet',
  props: {
    nowItem: {
      type: [Object, null],
      default: null,
    },
    mode: {
      type: String,
      default: '',
    },
  },
  components: {
    runTestDialog,
  },
  data() {
    return {
      fields: [],
    }
  },
  methods: {
    fetchFormFields() {
      let api
      if (this.mode == ButtonGetTriggerModuleEnum.Customer) {
        api = getCustomerFields
      } else if (this.mode == ButtonGetTriggerModuleEnum.Product) {
        api = getProductFields
      }
      api({
        isFromSetting: true
      }).then(res => {
        let { succ, data } = res;
        if (succ) {
          this.fields = filterFields(data);
        }
      })
    }
  },
  mounted() {
    this.fetchFormFields();
  },
  setup(props, { emit }) {
    const formDom = ref(null);
    const compilationTestDialog = ref(null);
    const codeField = ref({
      setting: {
        codeBlockConfig: {
          automaticOperation: 0,
          codeContent: props.nowItem.event[0].codeContent || '',
          resultAliasPath: [],
        }
      }
    });

    function customUrlValidator(rule, value, callback) {
      if (value) {
        if(!LINK_REG.test(value)) return callback(new Error(t('setting.buttonSet.text18')));
      }
      callback();
    }

    const triggerArr = computed(() => {
      let arr = commonStore.getButtonSetChooseUpdateTriggerList();
      return arr.map(i => {
        return {
          label: i.triggerName,
          value: i.id,
        };
      });
    });

    const taskTypeArr = computed(() => {
      let arr = [
        {
          label: t('common.connector.title.trigger'),
          value: ButtonSetDetailForButtonConcatEventEnum.Trigger,
        },
        {
          label: t('setting.enterprise.quickEntrance.customLink.title'),
          value: ButtonSetDetailForButtonConcatEventEnum.Linker,
        },
        {
          label: t('common.form.type.jsCodeBlock'),
          value: ButtonSetDetailForButtonConcatEventEnum.Code,
        },
      ];
      return arr;
    });

    // const realTriggerValue = computed(() => {
    //   let arr = props.nowItem.event;
    //   let item = arr.find(i => i.type === ButtonSetDetailForButtonConcatEventEnum.Trigger);
    //   return item?.execute[0] || '';
    // });

    function changeTrigger(val) {
      let res = val ? [val] : [];
      emit('changeTrigger', res);
    }

    function changeTaskType(val) {
      props.nowItem.event[0].execute = [];
      emit('changeBtnListEventType', val);
    }

    function changeLinker(val) {
      let res = val ? [val] : [];
      emit('changeLinker', res);
    }

    function changeCode(val) {
      props.nowItem.event[0].codeContent = val?.codeContent || '';
      emit('changeCode', val?.codeContent || '');
    }

    function openTestDialog() {
      codeField.value.setting.codeBlockConfig.codeContent = props.nowItem.event[0].codeContent || '';
      compilationTestDialog.value.visible = true;
    }

    async function validate() {
      try {
        let res = await formDom.value.validate();
        return Promise.resolve(res);
      } catch (error) {
        Promise.resolve(false);
      }
    }
    return {
      validate,
      customUrlValidator,
      formDom,
      triggerArr,
      taskTypeArr,
      changeTrigger,
      changeLinker,
      changeTaskType,
      changeCode,
      openTestDialog,
      codeField,
      compilationTestDialog,
      ButtonSetDetailForButtonConcatEventEnum
    };
  },
});
</script>
<style lang="scss" scoped>
.connect-set-box {
  .w-100-p {
    width: 100%;
  }
}
.connect-set-header {
  padding: 5px 16px;
  background-color: #f5f8fa;
}
.form-item-compilation {
  button {
    width: 100%;
  }
  p {
    font-size: 12px;
    color: #8c8c8c;
    margin-top: 8px;
  }
}
</style>
